<template>
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
      class="add-admin-form"
    >
      <el-form-item label="分类名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入分类名称"/>
      </el-form-item>
  
      <el-form-item label="排序" prop="sort" >
        <el-input
          v-model="form.sort"
          type="number"
          placeholder="排序"
        />
      </el-form-item>
  
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="form.status">
          <el-radio :label="1">启用</el-radio>
          <el-radio :label="0">禁用</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
  </template>
  
  <script setup>
  import { ref, reactive, watch } from 'vue';
  import { ElMessage } from 'element-plus';
  
  const props = defineProps({
    formData: {
      type: Object,
      default: () => null
    }
  });
  
  const formRef = ref(null);
  
  const form = reactive({
    name: '',
    sort: 0,
    status: 1
  });
  
  // 监听formData变化，更新表单数据
  watch(() => props.formData, (newVal) => {
    if (newVal) {
      Object.assign(form, newVal);
    }
  }, { immediate: true });
  
  // 重置表单
  const resetForm = () => {
    if (formRef.value) {
      formRef.value.resetFields();
    }
    Object.assign(form, {
        name: '',
        sort: 0,
        status: 1
    });
  };
  
  // 验证规则
  const rules = {
    name: [
      { required: true, message: '任务类名称', trigger: 'blur' },
      { min: 2, max: 20, message: '任务类名称长度在2到20个字符之间', trigger: 'blur' }
    ],
    sort: [
        { required: true, message: '排序', trigger: 'blur' },
        { 
            pattern: /^[0-9]\d*$/,  // 只允许输入正整数（不包括0）
            message: '请输入正确的整数',
            trigger: 'blur'
        }
    ],
    status: [
      { required: true, message: '请选择状态', trigger: 'change' }
    ]
  };
  
  const validateForm = async () => {
    try {
      await formRef.value.validate();
      return true;
    } catch (error) {
      ElMessage.error('请检查表单填写是否正确');
      return false;
    }
  };
  
  defineExpose({
    formRef,
    form,
    validateForm,
    resetForm
  });
  </script>
  
  <style scoped>
  .add-admin-form {
    padding: 20px;
  }
  </style> 